<template>
  <div class="page-field login">
    <div class="page-title">
      登陆
    </div>

    <div class="page-part form-body">
      <mt-field label="用户名" placeholder="请输入手机号或邮箱" type="text" v-model="username"></mt-field>
      <mt-field label="密码" placeholder="请输入密码" type="password" v-model="password"></mt-field>
    </div>

    <div class="page-part form-button">
      <mt-button type="primary" class="form-submit" v-on:click="login()" v-bind:disabled="!checkUsernameAndPass()">登陆</mt-button>
      <mt-button type="default" v-on:click="register()">注册</mt-button>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { Toast } from 'mint-ui';
import qs from 'qs';
import storeItem from '../utils/store';

export default {
  name: 'login',
  data() {
    return {
      username: '',
      password: '',
    };
  },
  methods: {
    login() {
      if (!this.checkUsernameAndPass()) {
        Toast({
          message: '用户名密码填写不完整',
          duration: 1500,
        });
        return;
      }

      axios.post('/user/login', qs.stringify({
        username: this.username,
        password: this.password,
      })).then((response) => {
        if (response.status === 200) {
          if (response.data.status === true) {
            storeItem.storeItem(response.data.data);
            storeItem.storeItem({
              token: response.data.token,
            });
            Toast({
              message: '登陆成功',
              duration: 1500,
            });
            setTimeout(() => {
              this.$router.push({
                name: 'Index',
              });
            }, 1500);
          } else {
            Toast({
              message: response.data.message,
              duration: 1500,
            });
          }
        }
      }).catch((err) => {
        Toast({
          message: err.message,
          duration: 1500,
        });
      });
    },
    register() {
      this.$router.push({
        name: 'Register',
      });
    },
    checkUsernameAndPass() {
      return (this.username !== '' && this.password !== '');
    },
  },
  watch: {
    username() {

    },
    password() {

    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
a {
  color: #42b983;
}

.form-button {
  margin-top: 20px;
}

.form-submit {
  margin-right: 40px;
}

.form-body {
  margin-top: 20px;
}
</style>
